package cn.ecasoft.util;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * @Author: LiangChun
 * @Description: 参数校验
 * @DateTime: 2023/2/2
 **/
public class BeanValidateUtil {

    private BeanValidateUtil(){}

    /**
     * java bean 数据校验
     * 参数符合要求,返回 null,否则返回错误原因
     *
     * @param target 目标 bean
     * @param <T>
     * @return
     */
    public static <T> String validate(T target){
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        Validator validator = factory.getValidator();
        Set<ConstraintViolation<T>> constraintViolations = validator.validate(target);
        Iterator<ConstraintViolation<T>> iterator = constraintViolations.iterator();
        while (iterator.hasNext()) {
            ConstraintViolation<T> error = iterator.next();
            return "["+error.getPropertyPath()+"]:"+error.getMessage();
        }
        return  null;
    }

    public static <T> String validate(List<T> target){
        for (T t:target){
            if(validate(t) != null){
                return validate(t);
            }
        }
        return null;
    }
}
